<template>
  <div>
    <form action="/">
      <van-search
        v-model="value"
        show-action
        background="#4fc08d"
        placeholder="请输入搜索关键词"
        @search="onSearch"
      >
        <template #action>
          <div @click="onSearch">搜索</div>
        </template>
      </van-search>
    </form>
    <div class="history">
      <div class="headerhd">
        <h4>历史记录</h4>
        <!-- 删除全部历史记录 -->
        <van-icon @click="deletaDate" name="delete" />
      </div>
      <ul>
        <li v-if="!historydata">111</li>
        <li 
          v-for="data in historydata"
          :key="data"
          @click="$router.push({
            path: '/searchresult',
            query: {
              value: data
            }
          })"
          >{{ data }}</li>
      </ul>
      
    </div>
  </div>
</template>

<script>
import { Dialog } from 'vant'
export default {
  data () {
    return {
      value: '',
      historydata: localStorage.getItem('data')?JSON.parse(localStorage.getItem('data')):[]
    }
  },
  methods: {
    // 删除全部历史记录
    deletaDate () {
      Dialog.confirm({
      title: '清除历史记录',
      message: '确认清除全部历史记录吗？',
    })
      .then(() => {
        this.historydata = []
        localStorage.clear()
      })
      
    },
    onSearch () {
      // 去掉历史记录重复项
      if(this.historydata.indexOf(this.value) !== -1){
        console.log(this.historydata.indexOf(this.value))
        this.historydata.splice(this.historydata.indexOf(this.value), 1)
        this.historydata.unshift(this.value)
      }else{
        this.historydata.unshift(this.value)
      }
      localStorage.setItem("data", JSON.stringify(this.historydata))
      this.$router.push({
        path: "/searchresult",
        query: {
          value: this.value
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .history{
    .headerhd{
      display: flex;
      justify-content: space-between;
      h4{
        font-size: 20px;
        margin: 5px 15px;
        color: rgb(92, 78, 78);
      }
      .van-icon{
        margin: 5px 15px;
        font-size: 30px;
      }
    }
    
    ul{
      display: flex;
      font-size: 16px;
      flex-wrap: wrap;
      li{
        margin: 0 5px;
        background: rgb(163, 154, 154);
        border-radius: 10px;
        padding:2px 5px;
      }
    }
  }
</style>